<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="费用归属部门" prop="deptId" label-width="110px">
                <el-tree-select
v-model="formData.deptId" :data="deptList" @change="deptIdChange" :props="defaultProps" check-strictly
                  node-key="id" placeholder="请选择费用归属部门" default-expand-all />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报销公司" prop="subjectName">
                <el-input v-model="formData.subjectName" placeholder="请输入报销公司名称" />
              </el-form-item>
            </el-col>
          
            <el-col :span="12">
              <el-form-item label="费用类型" prop="expenseType">
                <el-select v-model="formData.expenseType" @change="expenseTypeChange" placeholder="请选择费用类型" default-expand-all="true">
                  <el-option
v-for="dict in getStrDictOptions(DICT_TYPE.OA_EXPENSE_TYPE)" :key="dict.value"
                    :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="费用名称" prop="expenseName">
                <el-select v-model="formData.expenseName" placeholder="请选择费用名称">
                  <el-option
v-for="(item) in expenseNameDicts" :key="item.label" :label="item.label"
                    :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="付款人" prop="payerId">
                <PostUserSelect :userId="formData.payerId" :postId="formData.payerPostId" @node-change="payerChange" placeholder="请选择付款人" />
              </el-form-item>
            </el-col>
            
          </el-row> 
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="费用发生日期" prop="billDate">
                <el-date-picker
v-model="formData.billDate" type="date" value-format="YYYY-MM-DD"
                  placeholder="选择费用发生日期" />
              </el-form-item>
            </el-col>
             <el-col :span="8">
              <el-form-item label="报销金额" prop="invoiceAmount">
                <el-input-number
v-model="formData.invoiceAmount" :min="0" :max="99999999" :step="100"
                  placeholder="请输入报销金额" class="!w-100pct" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="有无发票" prop="hasInvoice">
                <el-checkbox v-model="formData.hasInvoice" :true-label="1" :false-label="0">有发票</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark" label-width="50px">
                <el-input v-model="formData.remark" placeholder="请输入备注" :rows="5" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="附件" prop="files" label-width="50px">
                <OaFileManager :folderDisabled="true" :initial-file-ids="formData.files" @file-select-success="fileSelectScccess" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item>
            <el-button :disabled="formLoading" class="w100px" @click="saveDraft">
              暂 存
            </el-button>
            <el-button :disabled="formLoading" class="w100px" type="primary" @click="submitForm">
              审 批
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
    </el-col>

    <!-- 审批相关：流程信息 -->
    <el-col :span="8">
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
ref="timelineRef" :activity-nodes="activityNodes" :show-status-icon="false"
          @select-user-confirm="selectUserConfirm" />
      </ContentWrap>
    </el-col>
  </el-row>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { ExpenseApi, ExpenseVO } from '@/api/oa/expense'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { defaultProps, handleTree } from '@/utils/tree'
// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import * as DeptApi from '@/api/system/dept'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'
// 导入用户选择组件
import UserSelect from '@/views/system/user/UserSelect.vue'
import PostUserSelect from '@/views/system/user/PostUserSelect.vue'

defineOptions({ name: 'OaExpenseCreate' })

const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由
const deptList = ref<any[]>([]) // 部门列表
const expenseNameDicts = ref<any[]>([]) // 费用名称列表
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const isDraftMode = ref(false) // 是否为编辑草稿模式
const formData = ref({
  id: undefined,
  userId: undefined,
  userName: undefined,
  deptId: undefined,
  deptName: undefined,
  subjectName: undefined,
  billNo: undefined,
  billDate: undefined,
  payDate: undefined,
  expenseType: undefined,
  expenseName: undefined,
  invoiceAmount: undefined,
  expenseAmount: undefined,
  hasInvoice: 0,
  remark: undefined,
  files: undefined as string | undefined,
  status: undefined,
  processInstanceId: undefined,
  creatorName: undefined,
  updaterName: undefined,
  // 付款人相关字段
  payerId: undefined as number | undefined,
  payerName: undefined as string | undefined,
  payerPostId: Number(import.meta.env.VITE_PAYER_POST_ID) as number | undefined,
})
const formRules = reactive({
  expenseName: [{ required: true, message: '费用名称不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '报销员工不能为空', trigger: 'change' }],
  userName: [{ required: true, message: '报销员工姓名不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '报销部门不能为空', trigger: 'change' }],
  deptName: [{ required: true, message: '报销部门名称不能为空', trigger: 'blur' }],
  subjectName: [{ required: true, message: '报销公司不能为空', trigger: 'change' }],
  billDate: [{ required: true, message: '费用发生日期不能为空', trigger: 'change' }],
  expenseType: [{ required: true, message: '费用类型不能为空', trigger: 'change' }],
  expenseAmount: [{ required: true, message: '付款金额不能为空', trigger: 'blur' }],
  payerId: [{ required: true, message: '付款人不能为空', trigger: 'change' }],
  // hasInvoice: [{ required: true, message: '请选择是否有发票', trigger: 'change' }],
  // 备注、附件、付款日期不做必填校验
})
const formRef = ref() // 表单 Ref

// 审批相关：变量
const processDefineKey = 'oa_expense' // 流程定义 Key
const startUserSelectTasks = ref<any[]>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<Record<string, number[]>>({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref<Record<string, number[]>>({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')
const findNodeById = (data: any[], id: string) => {
  for (const item of data) {
    if (item.id === id) return item
    if (item.children) {
      const found = findNodeById(item.children, id)
      if (found) return found
    }
  }
  return null
}
const deptIdChange = (value: string) => {
 const item  = findNodeById(deptList.value,value)
 formData.value.deptName = item?.name // 设置部门名称 
}

// 付款人选择处理
const payerChange = (userInfo: any) => {
  if (userInfo) {
    formData.value.payerId = userInfo.id
    formData.value.payerName = userInfo.nickname
  } else {
    formData.value.payerId = undefined
    formData.value.payerName = undefined
  }
}



/** 提交表单 */
const submitForm = async () => {
  // 1.1 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 1.2 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择${userTask.name}的审批人`)
      }
    }
  }

  // 2. 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as ExpenseVO
    // 审批相关：设置指定审批人
    if (startUserSelectTasks.value?.length > 0) {
      data.startUserSelectAssignees = startUserSelectAssignees.value
    }
    await ExpenseApi.createExpense(data)
    message.success('发起成功')
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ path: '/work/feiyong/expense' })
  } finally {
    formLoading.value = false
  }
}
const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',') || undefined
}
const expenseTypeChange = async (value: string, item: any) => {
  // TODO @小北：这里可以根据费用类型，动态加载费用名称
  console.log('费用类型变更', value, item)
  formData.value.expenseName = undefined // 清空费用名称
  expenseNameDicts.value = await getIntDictOptions(value)
}

/** 暂存操作 */
const saveDraft = async () => {
  // 1. 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 2. 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as unknown as ExpenseVO

    if (isDraftMode.value && formData.value.id) {
      // 编辑草稿
      await ExpenseApi.updateDraft(data)
      message.success('暂存成功')
    } else {
      // 新增草稿
      await ExpenseApi.saveDraft(data)
      message.success('暂存成功')
    }

    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ path: '/work/feiyong/expense' })
  } finally {
    formLoading.value = false
  }
}

/** 加载草稿数据 */
const loadDraftData = async (id: number) => {
  formLoading.value = true
  try {
    const data = await ExpenseApi.getExpense(id)

    console.log('=== 加载草稿数据 ===')
    console.log('原始数据:', data)
    console.log('billDate原始值:', data.billDate, '类型:', typeof data.billDate, '是否数组:', Array.isArray(data.billDate))

    // 处理日期字段 - 确保日期格式正确
    // 将各种可能的日期格式统一转换为 YYYY-MM-DD 字符串格式
    const formatDate = (dateValue: any): string | undefined => {
      if (!dateValue) return undefined

      // 如果是Date对象
      if (dateValue instanceof Date) {
        const result = dateValue.toISOString().split('T')[0]
        console.log('Date对象转换:', result)
        return result
      }

      // 如果是字符串
      if (typeof dateValue === 'string') {
        // ISO格式字符串，提取日期部分
        if (dateValue.includes('T')) {
          const result = dateValue.split('T')[0]
          console.log('ISO字符串转换:', result)
          return result
        }
        // 已经是 YYYY-MM-DD 格式
        if (/^\d{4}-\d{2}-\d{2}$/.test(dateValue)) {
          console.log('标准格式，直接使用:', dateValue)
          return dateValue
        }
      }

      // 如果是数组格式 [year, month, day]
      if (Array.isArray(dateValue) && dateValue.length >= 3) {
        const year = dateValue[0]
        const month = String(dateValue[1]).padStart(2, '0')
        const day = String(dateValue[2]).padStart(2, '0')
        const result = `${year}-${month}-${day}`
        console.log('数组格式转换:', dateValue, '=>', result)
        return result
      }

      // 其他情况尝试转换为Date再格式化
      try {
        const d = new Date(dateValue)
        if (!isNaN(d.getTime())) {
          const result = d.toISOString().split('T')[0]
          console.log('通用Date转换:', result)
          return result
        }
      } catch (e) {
        console.error('日期格式转换失败:', dateValue, e)
      }

      console.warn('无法识别的日期格式:', dateValue)
      return undefined
    }

    // 先赋值其他字段
    Object.assign(formData.value, data)

    // 单独处理日期字段，确保格式正确
    const billDateFormatted = formatDate(data.billDate)
    const payDateFormatted = formatDate(data.payDate)

    console.log('billDate格式化后:', billDateFormatted)
    console.log('payDate格式化后:', payDateFormatted)

    formData.value.billDate = billDateFormatted as any
    formData.value.payDate = payDateFormatted as any

    console.log('赋值后 formData.billDate:', formData.value.billDate)
    console.log('=== 加载完成 ===')

    isDraftMode.value = true

    // 如果有费用类型，加载费用名称选项
    if (data.expenseType) {
      expenseNameDicts.value = await getIntDictOptions(data.expenseType)
    }
  } finally {
    formLoading.value = false
  }
}
/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    // 构建流程变量，包含报销金额（用于条件判断和节点预测）
    const processVariables: Record<string, any> = {
      day: daysDifference()
    }

    // 如果有报销金额，传递给后端用于审批流程判断
    if (formData.value.invoiceAmount !== undefined && formData.value.invoiceAmount !== null) {
      processVariables.expenseAmount = formData.value.invoiceAmount
    }

    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      // TODO 小北：可以支持 processDefinitionKey 查询
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: JSON.stringify(processVariables) // 解决 GET 无法传递对象的问题，后端 String 再转 JSON
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

// 计算天数差
// TODO @小北：可以搞到 formatTime 里面去，然后看看 dayjs 里面有没有现成的方法，或者辅助计算的方法。
const daysDifference = () => {
  const oneDay = 24 * 60 * 60 * 1000 // 一天的毫秒数
  // 这里暂时返回0，因为费用报销没有开始和结束时间
  return 0
}

/** 初始化 */
onMounted(async () => {
  // 检查是否为编辑草稿模式
  const { query } = useRoute()
  if (query.id) {
    await loadDraftData(Number(query.id))
  }

  // TODO @小北：这里可以简化，统一通过 getApprovalDetail 处理么？
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())



  if (!processDefinitionDetail) {
    message.error('OA费用报销申请的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次, formData.value可改成实际业务中的特定字段 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 如果流程定义ID还未加载，则不调用审批详情（避免编辑草稿时报错）
      if (!processDefinitionId.value) {
        return
      }
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)
</script>
